package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Article;
import cn.wolfcode.trip.base.domain.Shop;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.ArticleMapper;
import cn.wolfcode.trip.base.mapper.ShopMapper;
import cn.wolfcode.trip.base.mapper.UserInfoMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.service.IShopService;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ShopServiceImpl implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    //设置购物订单为未支付的购物车
    public void saveShopCatOrder(Long articleId, int number, int totalCost) {
        User user = UserContext.getCurrentUser();
        Shop shop=new Shop();
        shop.setArticle(articleMapper.selectByPrimaryKey(articleId));
        shop.setUserInfo(userInfoMapper.selectByPrimaryKey(user.getId()));
        shop.setNumber(number);
        shop.setTotalCost(totalCost);
        //设置状态为购物车,未支付
        shop.setState(Shop.STATE_SHOPCAT);
        shopMapper.insert(shop);
    }

    public Shop selectShopCatByUserIdAndArticleId(Long userId, Long articleId) {
        return shopMapper.selectShopCatByUserIdAndArticleId(userId,articleId);
    }

    public void resultShopCatOrder(Long articleId, Integer resultCost) {
        //获取当前登录人
        User user = UserContext.getCurrentUser();
        //获取登录人拥有的总积分
        Integer integral = userMapper.selectByPrimaryKey(user.getId()).getIntegral();

        //比较拥有的积分与将要结算的积分
        if(resultCost<integral){
            User u =new User();
            u.setIntegral(integral-resultCost);
            u.setId(user.getId());
            userMapper.updateIntegral(u);
            shopMapper.updateByPrimaryKey(user.getId(),articleId);
        }else{
            throw new RuntimeException("您的积分不足");
        }

    }

    public List<Shop> getArticleDetailByUserId(Long userId) {
        return shopMapper.getArticleDetailByUserId(userId);
    }

    public List<Shop> getArticleByUserId(Long userId) {
        return shopMapper.getArticleByUserId(userId);
    }
}
